new Vue({
    el: '#app',
    data: {
        order: {
            orderId: '',
            createTime: '',
            payTime: '',
            status: -1, // 订单的数字状态
            statusLabel: '', // 订单状态的中文标签
            totalAmount: 0,
            remark: '',
            items: [] // 商品列表
        },
        address: {
            name: '',
            phone: '',
            region: '',
            address: ''
        },
        subtotal: 0, // 商品总额
        shippingFee: 0, // 运费
        discount: 0, // 优惠折扣
        paymentMethod: '在线支付', // 支付方式，暂时固定
        logisticsSteps: [ 
        ]
    },
    computed: {
        // 根据订单状态数字返回CSS类名
        statusClass() {
            switch (this.order.status) {
                case 0: return 'status-pending';    // 未支付
                case 1: return 'status-paid';       // 已支付
                case 2: return 'status-cancelled';  // 已取消
                case 3: return 'status-completed';  // 已完成
                default: return 'status-unknown';
            }
        }
    },
    methods: {
        // 获取URL中的订单ID
        getOrderIdFromUrl() {
            const params = new URLSearchParams(window.location.search);
            return params.get('orderId');
        },
        // 获取订单详情
        fetchOrderDetails() {
            const orderId = this.getOrderIdFromUrl();
            if (!orderId) {
                alert('缺少订单ID，无法获取订单详情。');
                return;
            }

            $.ajax({
                url: `http://localhost:8080/order/findOrderById?orderId=${encodeURIComponent(orderId)}`, 
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200 && res.data) {
                        const orderData = res.data;
                        this.order.orderId = orderData.orderId;
                        this.order.createTime = orderData.createTime;
                        this.order.payTime = orderData.payTime;
                        this.order.status = orderData.status; // 直接使用数字状态

                        // 根据数字状态设置中文标签
                        switch (orderData.status) {
                            case 0: this.order.statusLabel = '未支付'; break;
                            case 1: this.order.statusLabel = '已支付'; break;
                            case 2: this.order.statusLabel = '已取消'; break;
                            case 3: this.order.statusLabel = '已完成'; break;
                        }
                        
                        this.order.totalAmount = orderData.totalAmount || 0;
                        this.order.remark = orderData.remark || '无';
                        this.order.address = orderData.address || '无';
                        console.log(orderData.address);
                        // 处理收货地址信息
                        if (orderData.address) {
                            this.address.name = orderData.address.name;
                            this.address.phone = orderData.address.phone;
                            this.address.region = orderData.address.region;
                            this.address.address = orderData.address.address;
                        }

                        // 处理商品列表
                        if (orderData.commodityList && Array.isArray(orderData.commodityList)) {
                            this.order.items = orderData.commodityList.map(item => {
                                // 假设商品图片信息在 commodityPicture[0].commodityImageUrl
                                const imageUrlMatch = (item.commodityPicture && item.commodityPicture[0] && item.commodityPicture[0].commodityImageUrl) ?
                                                      item.commodityPicture[0].commodityImageUrl.match(/photo[\\/].+$/) :
                                                      null;
                                const imageUrl = imageUrlMatch ? '/' + imageUrlMatch[0] : '/photo/default.jpg'; // 使用默认图片
                                return {
                                    productId: item.commodityId,
                                    productName: item.commodityName,
                                    salePrice: item.commoditySalePrice,
                                    quantity: item.commodityNum,
                                    imageUrl: imageUrl
                                };
                            });
                            // 计算商品总额
                            this.subtotal = this.order.items.reduce((sum, item) => sum + (item.salePrice * item.quantity), 0).toFixed(2);
                        } else {
                            this.order.items = [];
                            this.subtotal = '0.00';
                        }

                        // 运费和折扣，如果后端有返回则更新
                        this.shippingFee = orderData.shippingFee || 0;
                        this.discount = orderData.discount || 0;
                        this.paymentMethod = orderData.paymentMethod || '在线支付'; // 确保 paymentMethod 是实际值
                        this.logisticsSteps = orderData.logisticsSteps || []; // 如果后端返回物流信息，则更新

                    } else {
                        alert('获取订单详情失败：' + (res.message || '未知错误'));
                        console.error('获取订单详情失败:', res);
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，获取订单详情失败。');
                    console.error('AJAX error fetching order details:', status, error);
                }
            });
        }
    },
    created() {
        this.fetchOrderDetails();
    }
});
